import SparkMD5 from 'spark-md5';
import { slice as sliceApi } from '@/services/system/upload';

// 特征值计算
export function calcMd5(file) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    let spark = new SparkMD5(); // 创建md5对象（基于SparkMD5）
    reader.readAsBinaryString(file); // myfile 对应上传的文件
    reader.onload = (e) => {
      let value = '';
      spark.appendBinary(e.target.result);
      value = spark.end();
      resolve(value);
    };
  });
}

// 文件分片
export function createChunk(file, size = 1 * 1024 * 1024) {
  const chunkList = [];
  let cur = 0;
  while (cur < file.size) {
    // 使用slice方法切片
    chunkList.push({ file: file.slice(cur, cur + size) });
    cur += size;
  }
  return chunkList;
}

// 文件上传
export async function upload({ data, file, filename, onProgress }) {
  const md5 = await calcMd5(file);
  const chunkFileList = createChunk(file);
  const chunks = chunkFileList.length;
  let res = { code: '200', msg: '未上传', data: {} };
  for (let index = 0; index < chunks; index++) {
    const item = chunkFileList[index];
    const formData = new FormData();
    formData.append('md5', md5);
    const chunk = index + 1;
    formData.append('chunk', chunk);
    formData.append('chunks', chunks);
    if (data) {
      Object.keys(data).forEach((key) => {
        formData.append(key, data[key]);
      });
    }
    formData.append('name', file.name);
    formData.append(filename, item.file);
    const chunk_md5 = await calcMd5(item.file);
    formData.append('chunk_md5', chunk_md5);
    res = await sliceApi(formData, {
      params: {},
    });
    const percent = Math.floor((chunk / chunks) * 100);
    if (res.code !== '200') {
      return res;
    }
    onProgress({ percent }, file);
  }
  return res;
}
